# coding=utf-8
import os
import configparser

import re
from flask import json, jsonify

from core.users import Users
from tools import convert
from tools.OperationError import OperationError
from tools.httpdoer import Request
from webapp.config import Config


class MasterInit:
    def masterInit(self, storeID):
        request = Request(Config.ERP_URL + "api/pos/masterInit")
        request.method = "post"  # 调用 _set_method
        request.timeout = 10  # 调用 _set_timeout
        request.path_params = None
        request.query = {"CP_C_STORE_ID": storeID}
        r = request.send(json=False)
        if r is None:
            res = {}
            res["code"] = -1
            res["message"] = "服务端没有返回数据"
            # 处理数据
            # object = json.loads(re.sub('\'', '\"', str(res)))
        else:
            self.setInfo(r)
            res = convert.to_dict(r.json)

        return res

    def setInfo(self, response):

        if response.status_code != 200:
            raise OperationError(-1, "服务端请求失败", response.text)

        if response.json == None:
            raise OperationError(-1, "服务器返回格式错误")  # print(type(res))

        res = convert.to_dict(response.json)  # print(type(res))
        if res["code"] == 0:
            message = res["message"]
            print(message)
            r_data = res.get("data", None)
            if r_data is None:
                raise OperationError(-1, "服务端返回的data数据为空")
            print(r_data)
            users = Users()
            users.saveUsersInfo(r_data)


if __name__ == "__main__":
    masterInit = MasterInit()
    r = masterInit.masterInit("206598864955")
    print(r)
